<?php
declare(strict_types=1);

namespace App\AdminApi\Module\Admin\Command;

use App\Common\Model\Admin\MenuModel;
use App\Sys;
use Hyperf\Command\Annotation\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Zms\Guard\AuthUnit;

#[Command]
class UpMenuAuthCommand extends \Hyperf\Command\Command
{
    /**
     * 执行的命令行
     *
     * @var null|string
     */
    protected ?string $name = 'app:up-admin-menu-auth';


    public function __construct(string $name = null)
    {
        parent::__construct($name);
        $this->setDescription('更新菜单路由绑定权限值');
    }


    public function handle()
    {
        $input = Sys::container(InputInterface::class);
        $output = Sys::container(OutputInterface::class);
        $authMapping = AuthUnit::collectMenuPermissions('admin');
        $paths = array_keys($authMapping);
        if (count($paths) === 0) {
            return parent::execute($input, $output);
        }
        $menu = MenuModel::whereIn('path', $paths)->get();
        $success = $error = 0;
        $this->info(PHP_EOL . PHP_EOL . '开始更新菜单权限值,请确保已更新缓存和代理类缓存');
        $progress = new ProgressBar($output, count($menu));
        $progress->start();
        /**
         * @var MenuModel $item
         */
        foreach ($menu as $item) {
            $item->node = $authMapping[$item->path] ?? [];
            if ($item->save()) {
                $success++;
            } else {
                $error++;
            }
            $progress->advance();
        }
        $progress->finish();
        $this->output->success("全限值已更新,{$success}成功更新个，{$error}个更新失败");
    }
}